<script setup>
import {computed, onMounted, reactive, ref, toRef, watch, watchEffect} from "vue";
import {baseUrl, reqInstance} from "@/utils/request/index.js";
import customerAddEdit from "@/views/customer/AddEdit.vue";
import dayjs from "dayjs";
import {message} from "ant-design-vue";
import {useLoginStore} from "@/sotre/useLoginStore.js";

const drawerTitle = ref("新增")
const customers = ref([])
const proTypeFees = ref([])

const visible = ref(false)

const emit = defineEmits(['create-completed'])
const fileList = ref([]);
const headers = {
  Authorization: useLoginStore().token,
};
const handleChange = info => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    formState.value.pre_attachment = info.file.response
    message.success(`文件上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`文件上传失败`);
  }

  // console.log("info.file",info)
};
const open = () => {
  visible.value = true
  getCustomers()
  getProjectTypes()
  getUsers()
}


const createOpen = () => {
  drawerTitle.value = "新增合同"
  formState.value = defaultFormData
  open()
}

let contract_year_contents = []
let updated_id = 0
const updateOpen = (data) => {
  updated_id = data.id
  contract_year_contents = data.contract_year_contents
  drawerTitle.value = "编辑合同"
  formState.value = {...formState.value, ...data}
  formState.value.market_user_ids = formState.value.contract_users.filter((item) => item.user_type === 0).map(item => item.user_id)
  formState.value.customer_id = formState.value.contract_customer.customer_id
  formState.value.sign_date_item = dayjs.unix(formState.value.sign_date)
  // fileList.value.push(formState.value.pre_attachment)
  fileList.value = []
  if (!!formState.value.pre_attachment) {
    fileList.value.push({
      uid: '2',
      name: formState.value.pre_attachment,
      status: 'done',
      url: baseUrl + "/" + formState.value.pre_attachment,
    })
  }
  formState.value.start_end = [dayjs.unix(formState.value.start_date), dayjs.unix(formState.value.end_date)]
  open()
}

const getCustomers = async () => {
  try {
    const res = await reqInstance({
      url: "/customer/all",
      method: "get",
    })
    customers.value = (res.data?.data ?? []).map((item) => {
      return {
        value: item.id,
        label: item.com_name
      }
    })
    console.log(customers.value);
  } catch (e) {

  }
}

const users = ref([])
const getUsers = async () => {
  try {
    const res = await reqInstance({
      url: "/user/all",
      method: "get",
    })
    users.value = (res.data?.data ?? []).map((item) => {
      return {
        value: item.user_id,
        label: item.name
      }
    })
  } catch (e) {

  }
}

const getProjectTypes = async () => {
  try {
    const res = await reqInstance({
      url: "/pro-type-fee/all",
      method: "get",
    })
    /**
     * {
     *     "id": 1,
     *     "type_title": "高企",
     *     "support_fixed_amount": true,
     *     "support_divide_amount": true,
     *     "created_at": "0001-01-01T00:00:00Z",
     *     "updated_at": "0001-01-01T00:00:00Z"
     * }
     */
    proTypeFees.value = (res.data?.data ?? []).map(({
                                                      id,
                                                      type_title,
                                                      support_fixed_amount,
                                                      support_divide_amount,
                                                    }) => {
      return {
        value: id,
        label: type_title,
        support_fixed_amount,
        support_divide_amount,
      }
    })
    console.log(proTypeFees);
  } catch (e) {

  }
}

const proTypeFeeMap = computed(() => {
  const r = {}
  Object.values(proTypeFees.value).forEach(({
                                              value,
                                              support_fixed_amount,
                                              support_divide_amount,
                                            }) => {
    r[value] = {
      support_fixed_amount,
      support_divide_amount,
    }
  })
  console.log('rrr', r)
  return r
})

const customerDrawRef = ref()

const addProType = () => {
  formState.value.contract_project_type_fees.push({
    project_type_setting_id: '',
    fixed_amount: '',
    divide_amount: '',
  })
}
const removeProType = (index) => {
  formState.value.contract_project_type_fees.splice(index, 1)
}

const afterOpenChange = bool => {
  console.log('open', bool);
};

const defaultFormData =  {
  customer_id: '',
  company_id: 0, // todo: 切换企业
  contact_name: "",
  contact_phone: "",
  project_name: "",
  sign_date: 0,
  sign_date_item: null,
  start_date: 0,
  end_date: 0,
  start_end: [],
  content: "",
  step: 0,
  pre_attachment:"",
  contract_project_type_fees: [
    // {
    //   project_type_setting_id: 0,
    //   fixed_amount: 0,
    //   divide_amount: 0,
    // }
  ],
  contract_year_contents: [
    // {
    //   year: 2024,
    //   content: "cccc",
    // }
  ],
  contract_users: [
    // {
    //   contract_id: '123',
    //   user_id: 0,
    //   user_type:0,
    // }
  ],
  market_user_ids: [],
}

const formState = ref(defaultFormData);


watchEffect((onCleanup) => {
  if (formState.value.start_end.length === 2) {
    const minusYear = formState.value.start_end[1].year() - formState.value.start_end[0].year() + 1
    for (let i = 0; i < minusYear; i++) {
      const year = formState.value.start_end[0].year() + i;
      if (!contract_year_contents.some(t => t.year === year)) {
        formState.value.contract_year_contents.push({
          year,
          content: "",
        })
      } else {
        formState.value.contract_year_contents.push(...contract_year_contents.filter(t => t.year === year))
      }
    }
    contract_year_contents = formState.value.contract_year_contents
  }
  onCleanup(() => {
    formState.value.contract_year_contents = []
  })
})


const doSave = async (saveType) => {
  formState.value.step = saveType === 0 ? 0 : 1;
  formState.value.start_date = formState.value.start_end[0].unix()
  formState.value.end_date = formState.value.start_end[1].unix()
  formState.value.sign_date = formState.value.sign_date_item.unix()
  formState.value.contract_project_type_fees.forEach((item) => {
    item.fixed_amount = parseFloat(item.fixed_amount)
    item.divide_amount = parseFloat(item.divide_amount)
  })

  if (drawerTitle.value === '新增合同') {
    await createSave()
  } else {
    await updateSave()
  }
}

const createSave = async () => {
  try {
    await reqInstance({
      url: "contract",
      method: "post",
      data: formState.value
    })
    emit('create-completed')
    visible.value = false
    message.success("保存成功")
  } catch (e) {

  }
}
const updateSave = async () => {
  try {
    await reqInstance({
      url: "contract/" + updated_id,
      method: "put",
      data: formState.value
    })
    emit('create-completed')
    visible.value = false
    message.success("保存成功")
  } catch (e) {

  }
}

defineExpose({createOpen, updateOpen})

</script>

<template>
  <a-drawer
      v-model:open="visible"
      class="custom-class"
      root-class-name="root-class-name"
      :root-style="{ color: 'blue' }"
      style="color: red"
      :title=drawerTitle
      placement="right"
  >
    <a-form layout="vertical" :model="formState">
      <a-form-item label="客户名称">
        <a-input-group compact>
          <a-select
              show-search v-model:value="formState.customer_id" :options="customers" style="width: calc(100% - 65px)"/>
          <a-button type="primary" @click="customerDrawRef.createOpen()">新增</a-button>
        </a-input-group>
      </a-form-item>
      <a-form-item label="对接人姓名">
        <a-input v-model:value="formState.contact_name" placeholder="请输入对接人姓名"/>
      </a-form-item>
      <a-form-item label="对接人电话">
        <a-input v-model:value="formState.contact_phone" placeholder="请输入对接人电话"/>
      </a-form-item>
      <a-form-item label="项目名称">
        <a-input v-model:value="formState.project_name" placeholder="请输入项目名称"/>
      </a-form-item>
      <a-form-item>
        <template #label>
          项目类型
          <a-button type="link" @click="addProType">新增</a-button>
        </template>
        <a-row class="span-title">
          <a-col flex="5">
            <span>
              项目类型
            </span>
          </a-col>
          <a-col flex="4">
            <span>
            固定总价
            </span>
          </a-col>
          <a-col flex="4">
            <span>
            分成
            </span>
          </a-col>
          <a-col flex="60px">
            <span>操作</span>
          </a-col>
        </a-row>
        <template v-for="(item, index) in formState.contract_project_type_fees">
          <a-row :gutter="4">

            <a-col flex="5">
              <a-select v-model:value="item.project_type_setting_id" :options="proTypeFees"></a-select>
            </a-col>
            <a-col flex="4">
              <a-input v-model:value="item.fixed_amount"
                       :disabled="!!item.project_type_setting_id ? !proTypeFeeMap[item.project_type_setting_id]?.['support_fixed_amount'] : false"></a-input>
            </a-col>
            <a-col flex="4">
              <a-input v-model:value="item.divide_amount"
                       :disabled="!!item.project_type_setting_id ? !proTypeFeeMap[item.project_type_setting_id]?.['support_divide_amount'] : false"></a-input>
            </a-col>
            <a-col flex="60px">
              <a-button danger type="link" @click="removeProType(index)">删除</a-button>
            </a-col>
          </a-row>
        </template>
      </a-form-item>
      <a-form-item label="签订日期">
        <a-date-picker v-model:value="formState.sign_date_item" placeholder="请选择签订日期"/>
      </a-form-item>
      <a-form-item label="合同周期">
        <a-range-picker v-model:value="formState.start_end" :bordered="false"/>
      </a-form-item>

      <template v-for="(item) in formState.contract_year_contents">
        <a-form-item :label="item.year + '年 服务内容'">
          <a-input v-model:value="item.content" placeholder=""/>
        </a-form-item>
      </template>
      <a-form-item label="市场负责人">
        <a-select mode="multiple" v-model:value="formState.market_user_ids" :options="users"></a-select>
      </a-form-item>
      <a-form-item label="合同详情">
        <a-textarea v-model:value="formState.content" placeholder="请输入合同详情"/>
      </a-form-item>
      <a-form-item label="合同附件（预审）">
        <a-upload
            v-model:file-list="fileList"
            name="file"
            :max-count="1"
            :action="baseUrl + '/file'"
            :headers="headers"
            @change="handleChange"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>

      </a-form-item>
      <a-form-item v-if="formState.step < 3">
        <a-button @click="doSave(0)">保存</a-button>
        <a-button type="primary" @click="doSave(1)">保存并提交</a-button>
      </a-form-item>
    </a-form>

    <customerAddEdit ref="customerDrawRef" @create-completed="getCustomers()"/>
  </a-drawer>

</template>

<style scoped>
.span-title {
  font-size: 12px;
  color: #666;
  text-align: center;
}
</style>